package com.abe.libcore.utils

import android.text.TextUtils
import com.abe.libcore.ConstantCore
import java.io.*
import java.text.SimpleDateFormat
import java.util.*


object DailyLogUtils {
    fun saveLocalLog(title: String, message: String, path: String) {
        try {
            val time = SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).format(Date())
            val fileName = "$title-$time.txt"
            FileUtils.createDir(path)
            val file = getLogFile(path, fileName)
            //追加写入内容
            addTxtToFileBuffered(file, message)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun saveLocalDailyLog(date: Date, msg: String, filePath: String) {
        var message: String = msg
        var path: String = filePath
        if (TextUtils.isEmpty(message)) message = ""
        if (TextUtils.isEmpty(path)) path = ConstantCore.FILE_ROOT_PATH
        try {
            //检查是否存在今天的日志文件，以日期为名
            val timeAll = SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).format(date)
            message = "$message******$timeAll"
            val time = SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(date)
            val fileName = time + ".txt"
            //文件夹检查，不存在则创建
            FileUtils.createDir(path)
            //文件不存在则创建
            val file = getSupportAttachFile(path, fileName, false, 0)
            //追加写入内容
            addTxtToFileBuffered(file, message)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getLogFile(path: String, fileName: String): File {
        val fullName = path + File.separator + fileName
        val file = File(path, fileName)
        if (!FileUtils.fileIsExists(fullName)) {
            FileUtils.createNewFile(path, fileName)
        }
        return file
    }

    /**
     * 检测文件大小，超过限制，分文件生成
     *
     * @param path      文件夹路径
     * @param fileName  文件名
     * @param isSupport 是否支持超额分文件存储
     * @param limitSizeNum isSupport为true是值为文件大小上限，单位为MB,默认为10
     */
    private fun getSupportAttachFile(path: String, fileName: String, isSupport: Boolean, limitSizeNum: Int): File {
        var limitSize = limitSizeNum
        val fullName = path + File.separator + fileName
        val file = File(path, fileName)
        if (!FileUtils.fileIsExists(fullName)) {
            FileUtils.createNewFile(path, fileName)
        } else {
            if (isSupport) {
                limitSize = if (limitSize <= 1 || limitSize >= 100) 10 else limitSize
                //检测文件是否超额
                val fileSize = FileSizeUtils.getFileOrFilesSize(fullName, FileSizeUtils.SIZE_TYPE_MB)
                //超额份文件
                if (fileSize > limitSize) {
                    var i = 1
                    var attachFileName = fileName + "_" + i
                    var attachFileFullName = path + File.separator + attachFileName
                    while (FileUtils.fileIsExists(attachFileFullName)) {
                        //检测分文件是否超额
                        val attachFileSize = FileSizeUtils.getFileOrFilesSize(fullName, FileSizeUtils.SIZE_TYPE_MB)
                        if (attachFileSize > limitSize) {
                            i++
                            attachFileName = fileName + "_" + i
                            attachFileFullName = path + File.separator + attachFileName
                        } else {
                            return File(attachFileFullName)
                        }
                    }
                    //已经存在的分文件都已超额，需要重新创建
                    val attachFile = File(attachFileFullName)
                    FileUtils.createNewFile(path, attachFileName)
                    return attachFile
                }
            }
        }
        return file
    }

    /**
     * 使用BufferedWriter进行文本内容的追加
     *
     * @param file    文件
     * @param content 内容
     */

    private fun addTxtToFileBuffered(file: File?, content: String) {
        //在文本文本中追加内容
        var out: BufferedWriter? = null
        try {
            //FileOutputStream(file, true),第二个参数为true是追加内容，false是覆盖
            out = BufferedWriter(OutputStreamWriter(FileOutputStream(file, true)))
            out.newLine()//换行
            out.write(content)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                if (out != null) out.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}